import request from '../../utils/request'
import { showError } from '../../utils/util'
import JwtUtil from '../../utils/jwt'  // 引入JWT解析工具

Page({
  data: {
    postList: [],
    currentCategory: '',
    page: 1,
    size: 10,
    hasMore: true,
    loading: false,
    isFirstLoad: true,
    userInfoReady: false
  },

  onLoad: function() {
    console.log('=== 首页开始加载 ===')
    
    // 检查全局数据
    var app = getApp()
    console.log('全局数据:', app.globalData)
    console.log('用户ID:', app.globalData.userId)
    
    // 尝试从token解析用户ID
    this.tryParseUserIdFromToken()
  },

  // 尝试从token解析用户ID
  tryParseUserIdFromToken: function() {
    const app = getApp()
    const token = wx.getStorageSync('token')
    
    if (token) {
      console.log('发现token，尝试解析用户ID')
      try {
        const userId = JwtUtil.getUserId(token)
        if (userId) {
          console.log('从token解析出用户ID:', userId)
          app.globalData.userId = userId
          app.globalData.userInfoReady = true
          this.setData({ userInfoReady: true })
          this.refreshPosts()
          return
        }
      } catch (error) {
        console.error('解析token失败:', error)
      }
    }
    
    // 如果解析失败或没有token，检查现有用户信息
    if (app.globalData.userInfo && app.globalData.userInfo.userId) {
      console.log('使用现有用户信息中的ID:', app.globalData.userInfo.userId)
      app.globalData.userId = app.globalData.userInfo.userId
      app.globalData.userInfoReady = true
      this.setData({ userInfoReady: true })
      this.refreshPosts()
    } else {
      console.log('没有用户ID，直接加载帖子')
      this.setData({ userInfoReady: true })
      this.refreshPosts()
    }
  },

  onShow: function() {
    console.log('首页 onShow')
    if (!this.data.isFirstLoad) {
      this.refreshPosts()
    }
  },

  onPullDownRefresh: function() {
    console.log('下拉刷新')
    var that = this
    this.refreshPosts().then(function() {
      wx.stopPullDownRefresh()
    })
  },

  onReachBottom: function() {
    console.log('上拉加载更多')
    if (this.data.hasMore && !this.data.loading) {
      this.loadMorePosts()
    }
  },

  // 刷新帖子列表
  refreshPosts: function() {
    console.log('开始刷新帖子')
    
    // 先重置状态，但不设置 loading
    this.setData({
      page: 1,
      postList: [],
      hasMore: true
    })
    
    // 直接调用加载数据，让 loadPostsData 自己管理 loading 状态
    return this.loadPostsData()
  },

  // 加载更多帖子
  loadMorePosts: function() {
    var that = this
    console.log('开始加载更多帖子')
    if (!this.data.hasMore || this.data.loading) {
      console.log('跳过加载更多: hasMore=', this.data.hasMore, 'loading=', this.data.loading)
      return Promise.resolve()
    }
    return this.loadPostsData()
  },

  // 加载帖子数据
  loadPostsData: function() {
    var that = this
    console.log('loadPostsData 开始执行')
    
    // 检查是否已经在加载
    if (this.data.loading) {
      console.log('正在加载中，跳过本次请求')
      return Promise.resolve()
    }
    
    this.setData({ loading: true })
    console.log('设置 loading 为 true')

    var params = {
      page: this.data.page,
      size: this.data.size
    }

    console.log('开始请求帖子数据，参数:', params)
    
    var requestPromise
    if (this.data.currentCategory) {
      console.log('请求分类帖子:', this.data.currentCategory)
      requestPromise = request.get('/posts/category/' + this.data.currentCategory, params)
    } else {
      console.log('请求全部帖子')
      requestPromise = request.get('/posts', params)
    }

    return requestPromise.then(function(result) {
      console.log('API返回结果:', result)

      // 处理不同的数据格式
      var posts = that.normalizePostsData(result)
      console.log('处理后的帖子数据:', posts)

      // 如果API返回空数据，使用模拟数据
      if (posts.length === 0) {
        console.log('API返回空数据，使用模拟数据')
        that.showMockData()
        return
      }

      // 处理点赞状态
      return that.processLikeStatus(posts).then(function(postsWithLikeStatus) {
        console.log('处理点赞状态后的数据:', postsWithLikeStatus)

        // 更新页面数据
        that.setData({
          postList: that.data.page === 1 ? postsWithLikeStatus : that.data.postList.concat(postsWithLikeStatus),
          page: that.data.page + 1,
          hasMore: posts.length >= that.data.size,
          isFirstLoad: false
        })
        
        console.log('页面数据更新完成:', that.data)
      })
    }).catch(function(error) {
      console.error('加载帖子失败:', error)
      
      // 如果是第一次加载失败，显示测试数据
      if (that.data.isFirstLoad) {
        console.log('第一次加载失败，显示模拟数据')
        that.showMockData()
        showError('网络连接失败，显示测试数据')
      } else {
        showError('加载失败，请重试')
      }
    }).then(function() {
      that.setData({ loading: false })
      console.log('设置 loading 为 false')
    })
  },

  // 标准化帖子数据格式
  normalizePostsData: function(result) {
    console.log('开始标准化数据:', result)
    
    // 如果直接返回数组
    if (Array.isArray(result)) {
      console.log('数据是数组，直接返回')
      return result
    }
    
    // 如果是对象格式
    if (result && typeof result === 'object') {
      // { data: [], code: 200 }
      if (Array.isArray(result.data)) {
        console.log('数据格式: data 数组')
        return result.data
      }
      // { records: [], code: 200 }
      if (Array.isArray(result.records)) {
        console.log('数据格式: records 数组')
        return result.records
      }
      // { list: [], code: 200 }
      if (Array.isArray(result.list)) {
        console.log('数据格式: list 数组')
        return result.list
      }
      // { items: [], code: 200 }
      if (Array.isArray(result.items)) {
        console.log('数据格式: items 数组')
        return result.items
      }
    }
    
    console.warn('未知的数据格式，返回空数组:', result)
    return []
  },

  // 处理点赞状态 - 优化版
  processLikeStatus: function(posts) {
    var that = this
    console.log('开始处理点赞状态，帖子数量:', posts.length)
    
    const app = getApp()
    const userId = app.globalData.userId
    
    console.log('当前用户ID:', userId)
    
    if (!posts || posts.length === 0) {
      console.log('没有帖子，跳过点赞状态处理')
      return Promise.resolve(posts.map(function(post) {
        return Object.assign({}, post, {
          isLiked: post.isLiked || false
        })
      }))
    }

    // 检查是否有用户ID，如果没有就跳过点赞检查
    if (!userId) {
      console.log('用户ID尚未获取，跳过点赞状态检查')
      return Promise.resolve(posts.map(function(post) {
        return Object.assign({}, post, {
          isLiked: post.isLiked || false
        })
      }))
    }
    
    var likePromises = posts.map(function(post) {
      // 如果已经有点赞状态，直接返回
      if (post.isLiked !== undefined) {
        return Promise.resolve(post)
      }
      
      // 请求点赞状态
      return request.get('/team/check-like', {
        postId: post.id,
        userId: userId
      }).then(function(likeStatus) {
        console.log('帖子', post.id, '的点赞状态:', likeStatus)
        return Object.assign({}, post, {
          isLiked: likeStatus.isLiked || false
        })
      }).catch(function(error) {
        console.warn('获取帖子', post.id, '的点赞状态失败:', error)
        return Object.assign({}, post, { 
          isLiked: false 
        })
      })
    })
    
    return Promise.all(likePromises).catch(function(error) {
      console.error('处理点赞状态失败:', error)
      return posts.map(function(post) {
        return Object.assign({}, post, {
          isLiked: post.isLiked || false
        })
      })
    })
  },

  // 显示模拟数据
  showMockData: function() {
    console.log('显示模拟数据')
    var mockPosts = [
      {
        id: 1,
        title: '周末篮球活动招募',
        content: '本周六下午3点，体育馆篮球场，欢迎喜欢篮球的朋友一起来玩！',
        author: '篮球爱好者',
        createTime: '2024-01-15',
        likeCount: 8,
        isLiked: false
      },
      {
        id: 2,
        title: '寻找读书会伙伴',
        content: '每月一次读书分享，目前正在读《三体》，欢迎加入讨论！',
        author: '书虫小张',
        createTime: '2024-01-14',
        likeCount: 15,
        isLiked: true
      },
      {
        id: 3,
        title: '英语学习小组',
        content: '每周三晚上线上英语角，练习口语，交流学习心得。',
        author: '英语达人',
        createTime: '2024-01-13',
        likeCount: 12,
        isLiked: false
      }
    ]

    this.setData({
      postList: mockPosts,
      hasMore: false,
      isFirstLoad: false,
      loading: false
    })
    console.log('模拟数据设置完成:', this.data)
  },

  // 分类切换
  onCategoryChange: function(e) {
    var category = e.currentTarget.dataset.category
    console.log('分类切换:', category)
    this.setData({
      currentCategory: category,
      page: 1,
      postList: [],
      hasMore: true
    })
    this.loadPostsData()
  },

  // 点赞状态变化
  onLikeChange: function(e) {
    var detail = e.detail
    var postId = detail.postId
    var isLiked = detail.isLiked
    var likeCount = detail.likeCount
    console.log('点赞状态变化:', { postId: postId, isLiked: isLiked, likeCount: likeCount })
    var postList = this.data.postList.map(function(post) {
      if (post.id === postId) {
        return Object.assign({}, post, {
          isLiked: isLiked,
          likeCount: likeCount !== undefined ? likeCount : (post.likeCount || 0) + (isLiked ? 1 : -1)
        })
      }
      return post
    })
    this.setData({ postList: postList })
  },

  // 创建帖子
  onCreatePost: function() {
    console.log('点击创建帖子')
    wx.navigateTo({
      url: '/pages/create-post/create-post'
    })
  },

  // 查看帖子详情
  onPostTap: function(e) {
    var postId = e.currentTarget.dataset.postId
    console.log('点击帖子:', postId)
    if (postId) {
      wx.navigateTo({
        url: '/pages/post-detail/post-detail?id=' + postId
      })
    }
  }
})